import { Injectable } from '@angular/core';
import { UserDTO } from '../model/user-dto';
import { Observable } from 'rxjs';
import { _HttpClient } from '@delon/theme';
import { QueryOptions } from '../util/model/query-options';
import { ApiPagedData } from '../util/model/api-paged-data';

@Injectable({
  providedIn: 'root',
})
export class UserService {
  /**
   * API的入口URL 建设单位
   */
  private static URL = '/api/authority/users';

  constructor(private http: _HttpClient) {}

  /**
   * 注册
   *
   * @param data 信息
   */
  register(data: UserDTO): Observable<UserDTO> {
    return this.http.post<UserDTO>(`${UserService.URL}/register?_allow_anonymous=true`, data);
  }

  /**
   * 新增
   *
   * @param data 信息
   */
  create(data: UserDTO): Observable<UserDTO> {
    return this.http.post<UserDTO>(`${UserService.URL}`, data);
  }

  /**
   * 修改用户
   *
   * @param item 新增信息
   * @param id id
   */
  update(item: UserDTO, id: string): Observable<UserDTO> {
    return this.http.put<UserDTO>(`${UserService.URL}/${id}`, item);
  }

  /**
   * 分页查询用户
   *
   * @param option 分页参数
   * @param name 用户名称
   */
  getOnePage(option: QueryOptions, name?: string): Observable<ApiPagedData<UserDTO>> {
    const params = {};
    Object.assign(params, option);
    Object.assign(params, name ? { name } : {});
    return this.http.get<ApiPagedData<UserDTO>>(UserService.URL, params);
  }

  /**
   * 根据ID查找用户
   *
   * @param id id
   */
  findById(id: string): Observable<UserDTO> {
    return this.http.get<UserDTO>(`${UserService.URL}/${id}`);
  }

  /**
   * 删除用户
   *
   * @param id 用户id
   */
  deleteById(id: string): Observable<any> {
    return this.http.delete(`${UserService.URL}/${id}`);
  }

  /**
   * 检查登录账号是否可用
   *
   * @account 登录账号
   * @param id 用户id
   */
  checkAccountUnique(account: string, id?: string): Observable<any> {
    const params = { account };
    Object.assign(params, id ? { id } : {});
    return this.http.get<any>(`${UserService.URL}/account-only?_allow_anonymous=true`, params);
  }

  /**
   * 检查邮箱是否可用
   *
   * @account 登录邮箱
   * @param id 用户id
   */
  checkEmailUnique(email: string, id?: string): Observable<any> {
    const params = { email };
    Object.assign(params, id ? { id } : {});
    return this.http.get<any>(`${UserService.URL}/email-only?_allow_anonymous=true`, params);
  }
}
